#include <QFile>
#include <QCoreApplication>
#include <QFileInfo>
#include "INCLUDE/FileUtils.h"
#include "INCLUDE/AnsiConverter.h"

int CloseHandle(QFile &hFile)
{
    hFile.close();
    return 1;
}

FILE* fopenu(const char *filename, const char *mode)
{
#ifdef Q_OS_WIN
    return fopen(filename, mode);
#else
    bool isUtf8 = false;
    const QString str = toQtStr(filename, &isUtf8);

    return isUtf8 ? fopen(filename, mode) : fopen(qUtf8Printable(str), mode);
#endif
}

FILE* fopenu(const wchar_t *filename, const wchar_t *mode)
{
#ifdef Q_OS_WIN
    return _wfopen(filename, mode);
#else
    return fopen(
        qUtf8Printable(QString::fromWCharArray(filename)),
        qUtf8Printable(QString::fromWCharArray(mode)));
#endif
}

long long GetFileSize(const QFile &file,void*)
{
    return file.size();
}

QString pathLevelUpToExe(const int n_levels)
{
    QFileInfo info(QCoreApplication::applicationFilePath());

    QString path = info.absolutePath();

    for (int i = 0; i < n_levels; ++i)
    {
        path = QFileInfo(path).absolutePath();
    }
    while (path.endsWith('\\') || path.endsWith('/'))
        path.chop(1);

    return path;
}

QString diskRoot()
{
#ifdef Q_OS_WIN
    return QCoreApplication::applicationFilePath().left(2); // returns disc:
#else
    return QDir::homePath();
#endif
}

QString fullNameExistingCase(const QString &dir_path, const QString &file_name, const QDir::Filters filters)
{
    const QDir directory(dir_path);
    const QString orig_name = directory.absoluteFilePath(file_name);

    if ((filters != QDir::Dirs) &&  QFile::exists(orig_name))
        return orig_name;
    else if ((filters == QDir::Dirs) && QDir(orig_name).exists())
        return orig_name;

    const QStringList files = directory.entryList(filters | QDir::NoDotAndDotDot);

    foreach (const QString &filename, files)
    {
        if (filename.compare(file_name, Qt::CaseInsensitive) == 0)
        {
            return directory.absoluteFilePath(filename);
        }
    }
    return directory.absoluteFilePath(file_name); // for not existin files return path as is. May be used for writing
}

AutoFile::AutoFile(FILE &rfile):
    file(rfile)
{
}

AutoFile::~AutoFile()
{
    fclose(&file);
}
